package opn.srn.command.load.parser.stream;

public class StringStream implements IStream {

	String data;
	int pos = 0;

	public StringStream(String data) {
		this.data = data;
	}

	@Override
	public void open() {
	}

	@Override
	public String readTill(char delimiter, boolean strictMode) throws Exception {
		String result;
		int length = data.length();

		if (pos >= length && strictMode == true) {
			throw new Exception("No more data to extract...");
		}

		int index = data.indexOf(delimiter, pos);
		if (index == -1) {
			result = data.substring(pos);
			pos = length;
		} else {
			result = data.substring(pos, index);
			pos = index + 1;
		}

		return result;
	}

	@Override
	public String readTill(char delimiter, char escapeChar, boolean strictMode) throws Exception {
		String result;
		int length = data.length();

		if (pos >= length && strictMode == true) {
			throw new Exception("No more data to extract...");
		}

		int index = findDelimiterIndex(delimiter, escapeChar, pos, strictMode);
		if (index == -1) {
			result = data.substring(pos);
			pos = length;
		} else {
			result = data.substring(pos, index);
			pos = index + 1;
		}

		return result;
	}

	private int findDelimiterIndex(char delimiter, char escapeChar, int startPos, boolean strictMode) throws Exception {
		int length = data.length();

		int escapeCharCount = 0;
		for (int index = startPos; index < length; index++) {
			char currentChar = data.charAt(index);
			if (currentChar == escapeChar) {
				escapeCharCount = (escapeCharCount == 0) ? 1 : 0;
			} else if (currentChar == delimiter && escapeCharCount == 0) {
				return index;
			}
		}

		if (escapeCharCount != 0 && strictMode == true) {
			throw new Exception(escapeChar + " not closed...");
		}

		return -1;
	}

	@Override
	public String readNChar(int noOfChar, boolean strictMode) throws Exception {
		int length = data.length();

		if (strictMode == true && (pos + noOfChar) > length) {
			throw new Exception("More number of characters expected(" + noOfChar + ") but available is "
					+ (length - pos));
		}
		String result = data.substring(pos, pos + noOfChar);
		pos += noOfChar;
		return result;
	}

	@Override
	public void close() {
	}

	public static void main(String[] args) throws Exception {
		StringStream stream = new StringStream("12345,\"6,7\",890");
		/*
		 * System.out.println(stream.readNChar(5, true)); System.out.println(stream.readNChar(2, true));
		 * System.out.println(stream.readNChar(3, true));
		 */
		System.out.println(stream.readTill(',', '"', true));
		System.out.println(stream.readTill(',', true));
		System.out.println(stream.readTill(',', true));
		System.out.println(stream.readTill(',', '"', true));
		System.out.println(stream.readTill(',', '"', false));

	}

}
